package com.westos.echufang.controller;

import com.westos.echufang.constants.DefaultRegex;
import com.westos.echufang.constants.LoginConstants;
import com.westos.echufang.pojo.entity.Admin;
import com.westos.echufang.pojo.entity.Employee;
import com.westos.echufang.pojo.vo.Login;
import com.westos.echufang.service.login.LoginServiceImpl;
import com.westos.echufang.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

@Controller
@Validated
public class LoginController {

    @Value("${links.chufangurl}")
    private String chufangurl;

    @Value("${links.yaopinurl}")
    private String yaopinurl;

    private final LoginServiceImpl loginService;

    private final CookieUtil cookieUtil;

    @Autowired
    public LoginController(LoginServiceImpl loginService, CookieUtil cookieUtil) {
        this.loginService = loginService;
        this.cookieUtil = cookieUtil;
    }

    @RequestMapping("/mainnew")
    public ModelAndView main(HttpSession session){

        String name;
        String job;

        Employee loginEmployee = (Employee) session.getAttribute("loginEmployee");
        Admin loginAdmin= (Admin) session.getAttribute("loginAdmin");

        if (loginEmployee!=null){
            job=loginEmployee.getJob();
            name=loginEmployee.getName();
        }else if (loginAdmin!=null){
            job="admin";
            name=loginAdmin.getName();
        }else {
            job="";
            name="";
        }


        ModelAndView mv=new ModelAndView();
        mv.addObject("yaopinurl",yaopinurl+"?job="+job+"&name="+name);
        mv.addObject("chufangurl",chufangurl+"?job="+job+"&name="+name);
        mv.setViewName("main");
        return mv;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(Login login, Model model, HttpSession session) {
        System.out.println("==============");
        System.out.println(chufangurl);
        System.out.println(yaopinurl);

        Integer dbmsg = loginService.login(login);
        if (dbmsg.equals(LoginConstants.LOGIN_PASSWORD_FALSE)) {
            model.addAttribute("loginMsg", "密码错误");
            //System.out.println(model.getAttribute("loginMsg"));
            return "login/index";
        } else if (dbmsg.equals(LoginConstants.LOGIN_SUCCESS_ADMIN)) {
            session.setAttribute("loginAdmin", loginService.getAdminByPh(login.getPhone()));
            //System.out.println(session.getAttribute("loginUser"));
            return "redirect:/mainnew";
        } else if (dbmsg.equals(LoginConstants.LOGIN_SUCCESS_EMPLOYEE)) {
            session.setAttribute("loginEmployee", loginService.getEmpByPh(login.getPhone()));
            //获得后台地址

            //System.out.println(session.getAttribute("loginUser"));
            return "redirect:/mainnew";
        } else {
            model.addAttribute("loginMsg", "手机号不存在");
            //System.out.println(model.getAttribute("loginMsg"));
            return "login/index";

        }
    }


    @RequestMapping("/phoneTest")
    public String phoneTest(@NotEmpty @Pattern(regexp = DefaultRegex.PHONE_REGEX) @RequestParam("phone") String phone, Model model, HttpSession session, HttpServletResponse response, HttpServletRequest request) {
        Cookie codeCookie = null;
        Cookie emailCookie = null;
        Cookie phoneCookie = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            switch (cookie.getName()) {
                case "code":
                    codeCookie = cookie;
                    break;
                case "email":
                    emailCookie = cookie;
                    break;
                case "phone":
                    phoneCookie = cookie;
                    break;
            }
        }


        if ((codeCookie == null || emailCookie == null || phoneCookie == null) || !phone.equals(phoneCookie.getValue())) {
            String findPwd = loginService.findPwd(phone);
            //System.out.println(code);
            if (findPwd.equals(LoginConstants.PHONE_TEST_FAIL)) {
                model.addAttribute("phoneTest", "手机号不存在");
                return "login/findPwd";
            } else {
                String code = findPwd.substring(0, 8);
                String email = findPwd.substring(8);
                session.setAttribute("phoneTest", phone);
                session.setAttribute("code", code);
                codeCookie = new Cookie("code", code);
                emailCookie = new Cookie("email", email);
                phoneCookie = new Cookie("phone", phone);
                codeCookie.setMaxAge(60 * 30);
                emailCookie.setMaxAge(60 * 30);
                phoneCookie.setMaxAge(60 * 30);
                codeCookie.setHttpOnly(true);
                emailCookie.setHttpOnly(true);
                phoneCookie.setHttpOnly(true);
                response.addCookie(codeCookie);
                response.addCookie(emailCookie);
                response.addCookie(phoneCookie);
                //System.out.println(email.replace(4,email.indexOf("@"),"******"));
                session.setAttribute("emailAddress", "验证码已发送至" + new StringBuilder(email).replace(4, email.indexOf("@"), "******"));
                return "login/mailVerification";
            }
        } else {
            session.setAttribute("phoneTest", phone);
            String code = codeCookie.getValue();
            String email = emailCookie.getValue();
            session.setAttribute("phoneTest", phone);
            session.setAttribute("code", code);
            session.setAttribute("emailAddress", "验证码已发送至" + new StringBuilder(email).replace(4, email.indexOf("@"), "******"));
            return "login/mailVerification";
        }

    }


    @RequestMapping(value = "/codecheck", method = RequestMethod.POST)
    public String mailVerification(@NotEmpty @Pattern(regexp = DefaultRegex.CODE_REGEX) @RequestParam("code") String codecheck, Model model, HttpSession session) {
        codecheck = codecheck.trim();
        String code = (String) session.getAttribute("code");
        if (!codecheck.equals(code)) {
            model.addAttribute("codeCheck", "验证码错误");
            return "login/mailVerification";
        } else {
            //System.out.println(session.getAttribute("phoneTest"));
            session.setAttribute("checked", "checked");
            return "redirect:/alterPwd";
        }
    }

    @RequestMapping(value = "/alterPassword", method = RequestMethod.POST)
    public String alterPwd(@NotEmpty @Pattern(regexp = DefaultRegex.PASSWORD_REGEX) @RequestParam("password") String password, @RequestParam("confirm") String confirm, Model model, HttpSession session, HttpServletResponse response, @CookieValue("code") Cookie codeCookie, @CookieValue("email") Cookie emailCookie, @CookieValue("phone") Cookie phoneCookie) {
        System.out.println(1111111111);
        if (confirm.equals(password)) {
            String phoneTest = (String) session.getAttribute("phoneTest");
            Integer alterPwd = loginService.alterPwd(phoneTest, confirm);
            if (alterPwd == 1) {
                session.removeAttribute("code");
                session.removeAttribute("phoneTest");
                session.removeAttribute("emailAddress");
                cookieUtil.removesCookies(response,codeCookie,emailCookie,phoneCookie);
                return "redirect:/alterSuccess";
            } else {
                model.addAttribute("alterPasswordError", "密码修改失败，请重新修改");
                return "login/alterPwd";
            }
        } else {
            model.addAttribute("alterPasswordError", "两次密码不一致！");
            return "login/alterPwd";
        }
    }
}
